using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Abp.UI;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.Application.Contracts.Customized.BuyerVerify;
using SOEI.Solution.Application.Contracts.Customized.BuyerVerify.Dtos;
using SOEI.Solution.DomainEntities.CustomerManagement.DomainService;
using SOEI.Solution.DomainEntities.CustomerManagement.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace SOEI.Solution.DomainEntities.CustomerManagement
{
    /// <summary>
    /// 【扩展模块】  <br/>
    /// 【功能描述】  ：XXX 模块<br/>
    /// 【创建日期】  ：2020.05.21 <br/>
    /// 【开发人员】  ：static残影<br/>
    ///</summary>
    [ApiExplorerSettings(GroupName = "Manager", IgnoreApi = false)]
    public class BuyerAppService : SolutionAppServiceBase, IBuyerAppService
    {
        /// <summary>
        ///【Buyer】仓储层
        /// </summary>
        private readonly IRepository<Buyer, long> _buyerRepository;

        /// <summary>
        ///【Buyer】领域服务
        /// </summary>
        private readonly IBuyerManager _buyerManager;

        public BuyerAppService(
            IRepository<Buyer, long> buyerRepository,
            IBuyerManager buyerManager
        )
        {
            _buyerRepository = buyerRepository;
            _buyerManager = buyerManager;
        }

        #region -------------------------------------------------辅助工具生成---------------------------------------------- 

        /// <summary>
        ///【客源管理-买方】获取的分页列表信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<PagedResultDto<BuyerListDto>> GetPaged(GetBuyersInput input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();

            var query = _buyerRepository.GetAll()
            ////模糊搜索 字段Name
            .WhereIf(!input.Name.IsNullOrWhiteSpace(), a => a.Name.Contains(input.Name))
            ////模糊搜索 字段IdNumber
            .WhereIf(!input.IdNumber.IsNullOrWhiteSpace(), a => a.IdNumber.Equals(input.IdNumber))
            ////模糊搜索 字段PreLocation
            .WhereIf(!input.PhoneNumber.IsNullOrWhiteSpace(), a => a.PhoneNumber.Equals(input.PhoneNumber))
            //精确搜索  字段UserTag
            .WhereIf(!input.UserTag.IsNullOrWhiteSpace(), a => a.UserTag.Equals(input.UserTag))
            ;
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var entityList = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            var entityListDtos = ObjectMapper.Map<List<BuyerListDto>>(entityList);

            return new PagedResultDto<BuyerListDto>(count, entityListDtos);
        }

        /// <summary>
        ///【客源管理-买方】通过指定id获取MemberListDto信息
        /// </summary>
        [AbpAuthorize()]
        public async Task<BuyerListDto> GetById(EntityDto<long> input)
        {
            //Thread.Sleep(2000);

            var entity = await _buyerRepository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<BuyerListDto>(entity);
            return dto;
        }

        /// <summary>
        ///【客源管理-买方】 获取编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<GetBuyerForEditOutput> GetForEdit(NullableIdDto<long> input)
        {
            var output = new GetBuyerForEditOutput();
            BuyerEditDto editDto;

            if (input.Id.HasValue)
            {
                var entity = await _buyerRepository.GetAsync(input.Id.Value);
                editDto = ObjectMapper.Map<BuyerEditDto>(entity);
            }
            else
            {
                editDto = new BuyerEditDto();
            }
            output.Buyer = editDto;
            return output;
        }
        /// <summary>
        ///【客源管理-买方】 添加或者修改的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task CreateOrUpdate(CreateOrUpdateBuyerInput input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();

            if (input.Buyer.Id.HasValue)
            {
                await Update(input.Buyer);
            }
            else
            {
                await Create(input.Buyer);
            }
        }
        /// <summary>
        ///【客源管理-买方】新增
        /// </summary>
        [AbpAuthorize()]
        protected virtual async Task<BuyerEditDto> Create(BuyerEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var Result = await _buyerManager.IsExistAsync(input.IdNumber);
            //根据身份证号查询该买受人是否在本经纪机构登记过
            //var Result = await _buyerManager.FindByIdNumberAsync(BuyerEditDto input);

            if (Result == true)
            {
                throw new Exception("该买受人已经登记过信息，请勿重复登记");
            }
            var entity = ObjectMapper.Map<Buyer>(input);
            //调用领域服务
            entity = await _buyerManager.CreateAsync(entity);

            var dto = ObjectMapper.Map<BuyerEditDto>(entity);
            return dto;
        }

        /// <summary>
        ///【客源管理-买方】编辑
        /// </summary>
        [AbpAuthorize()]
        protected virtual async Task Update(BuyerEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            var key = input.Id.Value;
            var entity = await _buyerRepository.GetAsync(key);
            //  input.MapTo(entity);
            //将input属性的值赋值到entity中
            ObjectMapper.Map(input, entity);
            await _buyerManager.UpdateAsync(entity);
        }

        /// <summary>
        ///【客源管理-买方】删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task Delete(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            if (input != null)
            {
                // var entity = await _buyerRepository.GetAsync(input.Id);
                var result = await _buyerManager.IsExistAsync(input.Id);
                if (result == true)
                {
                    await _buyerManager.DeleteAsync(input.Id);
                }
                else
                {
                    throw new Exception("该用户不存在");
                }
            }
        }

        /// <summary>
        ///【客源管理-买方】 批量删除Member的方法
        /// </summary>
        [AbpAuthorize()]
        public async Task BatchDelete(List<long> input)
        {
            // TODO:批量删除前的逻辑判断，是否允许删除
            if (input.Count > 0 && input != null)
            {
                await _buyerManager.BatchDelete(input);
            }
        }

        #endregion

        #region -------------------------------------------------用户自定义------------------------------------------------
        /*请在此扩展应用服务实现*/

        public async Task<GetVerifyBuyerIsExitOutput> GetForCheck(CheckVerifyInput input)
        {
            //1. 获取当前登录的用户信息（）
            //2. 判断当前登录 是否经济机构用户
            await GetPersonChecker();
            var Output = new GetVerifyBuyerIsExitOutput();
            Output.HsaBuyer = await _buyerManager.IsExistAsync(input.IdNumber);
            if (Output.HsaBuyer == true)
            {
                throw new Exception("该买受人已经登记过信息，请勿重复登记");
            }
            else
            {

            }
            return Output;
        }
        #endregion
    }
}
